// 产品分类管理API服务
const express = require('express');
const router = express.Router();
const ProductCategory = require('../models/ProductCategory');

// 获取所有分类
router.get('/product-categories', async (req, res) => {
    try {
        const {
            page = 1,
            limit = 50,
            status = '',
            parent_id,
            sortBy = 'sort_order',
            sortOrder = 'ASC'
        } = req.query;
        
        const result = await ProductCategory.findAll({
            page: parseInt(page),
            limit: parseInt(limit),
            status,
            parent_id: parent_id !== undefined ? parseInt(parent_id) : undefined,
            sortBy,
            sortOrder
        });
        
        res.json({
            success: true,
            data: result.data,
            pagination: result.pagination
        });
    } catch (error) {
        console.error('获取分类列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类列表失败'
        });
    }
});

// 获取分类树
router.get('/product-categories/tree', async (req, res) => {
    try {
        const categoryTree = await ProductCategory.getCategoryTree();
        
        res.json({
            success: true,
            data: categoryTree
        });
    } catch (error) {
        console.error('获取分类树失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类树失败'
        });
    }
});

// 获取单个分类
router.get('/product-categories/:id', async (req, res) => {
    try {
        const category = await ProductCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        res.json({
            success: true,
            data: category
        });
    } catch (error) {
        console.error('获取分类失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类失败'
        });
    }
});

// 创建分类
router.post('/product-categories', async (req, res) => {
    try {
        const {
            name_en,
            name_zh,
            name_de,
            name_fr,
            name_es,
            description,
            parent_id,
            sort_order,
            status
        } = req.body;
        
        // 验证必填字段
        if (!name_en) {
            return res.status(400).json({
                success: false,
                message: '英文名称是必填项'
            });
        }
        
        const category = await ProductCategory.create({
            name_en,
            name_zh,
            name_de,
            name_fr,
            name_es,
            description,
            parent_id,
            sort_order,
            status
        });
        
        res.status(201).json({
            success: true,
            message: '分类创建成功',
            data: category
        });
    } catch (error) {
        console.error('创建分类失败:', error);
        res.status(500).json({
            success: false,
            message: '创建分类失败'
        });
    }
});

// 更新分类
router.put('/product-categories/:id', async (req, res) => {
    try {
        const category = await ProductCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        await category.update(req.body);
        
        res.json({
            success: true,
            message: '分类更新成功',
            data: category
        });
    } catch (error) {
        console.error('更新分类失败:', error);
        res.status(500).json({
            success: false,
            message: '更新分类失败'
        });
    }
});

// 删除分类
router.delete('/product-categories/:id', async (req, res) => {
    try {
        const category = await ProductCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        await category.delete();
        
        res.json({
            success: true,
            message: '分类删除成功'
        });
    } catch (error) {
        console.error('删除分类失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除分类失败'
        });
    }
});

// 获取分类统计
router.get('/product-categories/:id/stats', async (req, res) => {
    try {
        const categoryId = parseInt(req.params.id);
        
        // 获取分类下的产品数量
        const productCountQuery = 'SELECT COUNT(*) FROM products WHERE category_id = $1 AND status = $2';
        const productCountResult = await require('../config/database').postgresPool.query(
            productCountQuery, 
            [categoryId, 'active']
        );
        
        // 获取子分类数量
        const subcategoryCountQuery = 'SELECT COUNT(*) FROM product_categories WHERE parent_id = $1 AND status = $2';
        const subcategoryCountResult = await require('../config/database').postgresPool.query(
            subcategoryCountQuery,
            [categoryId, 'active']
        );
        
        res.json({
            success: true,
            data: {
                product_count: parseInt(productCountResult.rows[0].count),
                subcategory_count: parseInt(subcategoryCountResult.rows[0].count)
            }
        });
    } catch (error) {
        console.error('获取分类统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类统计失败'
        });
    }
});

module.exports = router;